package org.fujie.plugin.cloud.face.provider.init;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.fujie.plugin.cloud.comm.exception.IdCardScanException;
import org.fujie.plugin.cloud.comm.util.JsonUtil;
import org.fujie.plugin.cloud.core.provider.config.BaseConfig;
import org.fujie.plugin.cloud.core.provider.factory.BaseFactory;
import org.fujie.plugin.cloud.core.provider.factory.FactoryHolder;
import org.fujie.plugin.cloud.core.provider.service.BaseService;
import org.fujie.plugin.cloud.face.ProvideHelper;
import org.fujie.plugin.cloud.face.aliyun.factory.AliIdCardFactory;
import org.fujie.plugin.cloud.face.baidu.factory.BaiduIdCardFactory;
import org.fujie.plugin.cloud.face.tencent.factory.TencentIdCardFactory;

import java.util.Map;

/**
 * @author slm
 * @description 身份证服务初始化流程设置
 */
public class IdCardInitializer {

    private final Map<String, Map<String, Object>> server;
    public IdCardInitializer(Map<String, Map<String, Object>> server) {
        this.server = server;
        init();
    }


    private void init() {

        if (MapUtil.isNotEmpty(server)) {
            /*注册工厂*/
            registerDefaultFactory();

            for (String configId : server.keySet()) {

                Map<String, Object> configMap = server.get(configId);

                Object supplier = configMap.get("supplier");

                if (ObjectUtil.isNull(supplier)) {
                    throw new IdCardScanException().setMessage("初始化失败,服务商标识为空,请检查配置文件");
                }
                BaseFactory<? extends BaseService, ? extends BaseConfig> baseFactory = FactoryHolder.getFactory(StrUtil.toString(supplier));

                if (ObjectUtil.isNull(baseFactory)) {
                    throw new IdCardScanException().setMessage("初始化云服务商-$s失败,不支持的服务商类型");
                }
                /*按配置文件初始化服务*/
                BaseConfig config = JsonUtil.convertToBean(configMap, baseFactory.getConfigClass());
                ProvideHelper.register(config);
            }
        }
    }

    private void registerDefaultFactory(){

        FactoryHolder.registerFactory(AliIdCardFactory.getInstance());
        FactoryHolder.registerFactory(BaiduIdCardFactory.getInstance());
        FactoryHolder.registerFactory(TencentIdCardFactory.getInstance());
    }


}
